package com.xxx.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import com.xxx.bean.PageBean;
import com.xxx.bean.SessionBean;
import com.xxx.util.SessionSerializableUtils;

/**
 * 自定义sessionDAO（将session持久化到db中）
 */
public class MySessionDaoImpl extends CachingSessionDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;

	@Override
	public Serializable doCreate(Session session) {
		Serializable sessionId = generateSessionId(session);
		assignSessionId(session, sessionId);
		String sql = "insert into sessions(id, session) values(?,?)";
		jdbcTemplate.update(sql, sessionId, SessionSerializableUtils.serialize(session));
		return session.getId();
	}

	@Override
	public void doDelete(Session session) {
		String sql = "delete from sessions where id=?";
		jdbcTemplate.update(sql, session.getId());
	}
	
	@Override
	public void doUpdate(Session session) {
		if(session instanceof ValidatingSession && !((ValidatingSession)session).isValid()) {
			return; //如果会话过期/停止没必要再更新了
		}
		String sql = "update sessions set session=? where id=?";
		jdbcTemplate.update(sql, SessionSerializableUtils.serialize(session), session.getId());
	}

	@Override
	public Session doReadSession(Serializable sessionId) {
		String sql = "select session from sessions where id=?";
		List<String> sessionStrList = jdbcTemplate.queryForList(sql, String.class, sessionId);
		if(sessionStrList.size() == 0) {
			return null;
		}
        return SessionSerializableUtils.deserialize(sessionStrList.get(0)); // 只返回第一条记录
	}

	/**
	 * 获取活动session总数量
	 */
	public int getActiveSessionsCount() {
		String sql = "select count(*) from sessions";
		int sessionCount = jdbcTemplate.queryForObject(sql, Integer.class);
		return sessionCount;
	}
	
	/**
	 * 分页获取活动session列表
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Session> getActiveSessionsByPage(int pageNo, int pageSize) {
		PageBean pageBean = new PageBean(pageNo, pageSize); // 分页信息
		int offset = pageBean.getOffset();
		int size = pageBean.getSize();
		String sql = "select id, session from sessions limit ?, ?";
		Object [] args = {offset, size};
		List<SessionBean> list = jdbcTemplate.query(sql, args, new BeanPropertyRowMapper(SessionBean.class));
		if(CollectionUtils.isEmpty(list)) {
			return null;
		}
		List<Session> result = new ArrayList<>();
		Session session;
		for(SessionBean bean : list) {
			session = SessionSerializableUtils.deserialize(bean.getSession());
			result.add(session);
		}
		return result;
	}


}
